#include "base/logging.h"
#include "base/config_reader.h"

#include "ask_request.h"
#include "dump_request.h"
#include "auto_reply_cache.h"

#include "fcgi_service/fcgi_service.h"
using namespace fcgi;

namespace im {
namespace fcgi {

class ImRequestFactory : public RequestFactory {
public:
  virtual RequestPtr Create(FCGX_Request * r) {
    char * path = FCGX_GetParam("SCRIPT_NAME", r->envp);
    RequestPtr req;
    if (path) {
      if (strcmp(path, "/jdrobot/ask") == 0) {
        req = RequestPtr(new AskRequest(r));
      } else if (strcmp(path, "/jdrobot/dump") == 0) {
        req = RequestPtr(new DumpRequest(r));
      }
    }
    return req;
  }
};

}
}


int main(int argc, char **argv) {
  char * conf_file = "../conf/im_jd_robot_service.conf";
  char opt;
  while ((opt = getopt(argc, argv, "c:")) != -1) {
    switch (opt) {
    case 'c':
      conf_file = optarg;
      break;
    default:
      std::cerr << "Unknown option " << optopt << std::endl;
      return 1;
    }
  }

  ConfigReader cfg(conf_file);
  if (!cfg) {
    std::cerr << "Config file " << conf_file << " read error!" << std::endl;
    return 1;
  }
  im::AutoReplyCache::Instance().Reload();
  LOG_INIT(cfg.Get("log4cplus", "file"), cfg.Get("log4cplus", "level"));

  std::string bind_addr = cfg.Get("im_jd_robot_service", "bind");
  LOG_INFO("listens on port " << bind_addr);
  FcgiServer * fcgi_server = new FcgiServer(bind_addr, 128);
  fcgi_server->RegisterRequestFactory(RequestFactoryPtr(new im::fcgi::ImRequestFactory()));
  fcgi_server->Start(true); // 本线程也处理 fcgi 请求，不退出
  return 0;
}

